import { Meteor } from 'meteor/meteor';
import { LinksCollection } from '/imports/api/links';
import { MonitorCollection } from '/imports/api/monitor';
import { wrappedExec } from 'js-utils-new/dist/index.cjs'

function insertLink({ title, url }) {
  LinksCollection.insert({title, url, createdAt: new Date()});
}

const jobs = [
    {
        key: '约仓python后台',
        check: async () => {
            const result = await wrappedExec(' ssh ubuntu@175.178.205.102 "ps -elf |grep python"')
            return ( !!result.match(new RegExp('restful_v3_2.py')) &&
                (!!result.match(new RegExp('secondary_features.py'))) &&
                (!!result.match(new RegExp('sync_seller_serial_inbound.py'))))
        }
    },
    {
        key: '22约仓空间',
        check: async () => {
            return (await wrappedExec("ssh ubuntu@43.135.165.22 df -h |grep vda|awk '{print \$5}'")).trim()
        }
    },
    {
        key: 'jenkins空间',
        check: async () => {
            return (await wrappedExec("ssh ubuntu@119.91.87.199 df -h |grep vda1|awk '{print \$5}'")).trim()
        }
    }
]

async function checkJobs() {
    let results = []
    for (let job of jobs) {
        const result = await job.check();
        results.push({key: job.key, value: result})
    }
    return results
}


async function check() {

  console.log('check');
    Meteor.setInterval(async () => {
        // MonitorCollection.update({key: '约仓状态'},{$set: {value: false, t: new Date()} }, {upsert: true});
        // wrappedExec("ssh ubuntu@119.91.87.199 df -h |grep vda1|awk '{print \$5}'").then(res => {
        //     MonitorCollection.update({key: 'jenkins空间'},{$set: {value: res.trim(), t: new Date()} }, {upsert: true});
        // })
        const results = await checkJobs();
        results.forEach(({key, value}) => {
            MonitorCollection.update({key},{$set: {value, t: new Date()} }, {upsert: true});
        })

    }, 10000)
}



Meteor.startup(() => {
  // If the Links collection is empty, add some data.
  if (LinksCollection.find().count() === 0) {
    insertLink({
      title: 'Do the Tutorial',
      url: 'https://www.meteor.com/tutorials/react/creating-an-app'
    });

    insertLink({
      title: 'Follow the Guide',
      url: 'http://guide.meteor.com'
    });

    insertLink({
      title: 'Read the Docs',
      url: 'https://docs.meteor.com'
    });

    insertLink({
      title: 'Discussions',
      url: 'https://forums.meteor.com'
    });
  }

    check()

});
